package com.kotle.baselib.mvvm;

import android.arch.lifecycle.ViewModelProviders;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import java.lang.reflect.ParameterizedType;

/**
 * Created by Kotle on 2017/6/28.
 * MVVM模式的父类Activity
 * T：对应的ViewModel,如果没有，传入默认的BaseViewModel
 * P：根据xml文件生成的ViewDataBinding
 */

public abstract class BaseMvvmActivity<T extends BaseViewModel, P extends ViewDataBinding>
        extends AppCompatActivity {
    private P mBinding;//bingding对象
    private T mViewModel;//viewModel对象

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ktInit();
    }

    final protected void ktInit() {
        mBinding = DataBindingUtil.setContentView(this, getLayoutRes());
        Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        mViewModel = ViewModelProviders.of(this).get(entityClass);
        onObserve(mViewModel);
    }

    protected abstract int getLayoutRes();

    protected abstract void onObserve(T viewModel);
    /**
     * @return 返回binding对象
     */
    protected P getBinding() {
        return mBinding;
    }

    /**
     * @return viewModel对象
     */
    protected T getViewModel() {
        if (mViewModel == null) {
            throw new IllegalArgumentException("使用ViewModel前，必须先在createViewModel（）返回一个非NULL的对象");
        }
        return mViewModel;
    }

}
